<?php

namespace app\console\controller;

namespace app\console\controller;

use think\Session;
use think\Url;
use think\Cache;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\Ad as AdModel;
use app\console\model\Gift as Model;
use app\common\trilateral\Classify as ClassifyAlias;
use think\Db;
use think\View;

class Gift extends Controller
{


    /**
     * 前置方法
     */
    protected $beforeActionList = [
        'clearCache' => ['only'],
        'default_content' => ['create','update']
    ];


    /**
     * 广告位列表
     */
    public function index($pa = 10)
    {
        $param = Request::instance()->param();
        $where = [];

        if(!empty($param['title'])) $where['title'] = ['like','%'.$param['title'].'%'];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode(' / ', $param['interval_timer']);
            $where['create_time'] = ['between time', [($interval_timer[0]), ($interval_timer[1])]];
        }

        $data = Model::order(['sort' => 'asc','id' => 'desc'])->where($where)->paginate($pa,false,['query' => $param]);

        if(isset($param['export'])){
            $this->push_coupon($data);
        }
        return $this->fetch('', [
            'data' => $data,

        ]);
    }

    public function default_content(){
        $default_content = Db::name('single')
            ->order(['sort' => 'asc','id' => 'asc'])
            ->where('parent_id',1)
            ->where('auding_status',2)
            ->where('is_delete',1)
            ->select();
        View::share('default_content',$default_content);
    }

    public function single2($id){
        $default_content = Db::name('single')
            ->order(['sort' => 'asc','id' => 'asc'])
            ->where('parent_id',$id)
            ->where('auding_status',2)
            ->where('is_delete',1)
            ->field('id,cat_name')
            ->select();
        return ($default_content);
    }



    public function push_coupon($data,$name = '礼包导出')
    {

        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '科目代码')
            ->setCellValue('B1', '借贷方(绿色借方-灰色贷方)')
            ->setCellValue('C1', 'ID')
            ->setCellValue('D1', '礼包名称')
            ->setCellValue('E1', '礼包价格')
            ->setCellValue('F1', '总次数')
            ->setCellValue('G1', '促销时间')
            ->setCellValue('H1', '销量')
            ->setCellValue('I1', '创建时间')
            ;
        $sheet1 = [];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['code'])
                ->setCellValue('B' . $num, $v['dc_text'])
                ->setCellValue('C' . $num, $v['id'])
                ->setCellValue('D' . $num, $v['title'])
                ->setCellValue('E' . $num, $v['sale_price'])
                ->setCellValue('F' . $num, $v['count'])
                ->setCellValue('G' . $num, $v['start_time'].'-'.$v['end_time'])
                ->setCellValue('H' . $num, $v['sale_number'])
                ->setCellValue('I' . $num, $v['create_time'])
               ;
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('礼包导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 栏目状态改变
     */
    public function dc($id, Request $request, Model $model)
    {
        $id = $request->instance()->param('id');

        $status = $model->where('id', $id)->value('dc') == '1' ? 2 : 1;

        if ($model->where('id', $id)->update(['dc' => $status])) {
            return $status;
        }
        return false;
    }


    /**
     * 广告位创建
     */
    public function create(Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();
            if (!empty($data['single_content']) && count($data['single_content']) != count(array_unique($data['single_content']))) {
                fail('不能添加重复分类');
            }
//            // 验证
//            $validate = Loader::validate('AdType');
//            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = $model->allowField(true)->save($data);

            if ($dispose) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }

        $single_list = \app\console\model\Single::order(['sort' => 'asc','id' => 'asc'])->where(['auding_status' =>2,'is_delete'=>1])->where('parent_id',0)->select();
        $default_content = Db::name('single')->order(['sort' => 'asc','id' => 'asc'])->where('parent_id',1)->select();
        $single_list = getMenuTree($single_list);
        return $this->fetch('create', [
            'single_list' => json_encode($single_list),
//            'default_content' => json_encode($default_content),
            'gift_count' => []
        ]);

    }

    public function code(){
        $param = Request::instance()->param()['code'];

        if(!empty($param)){

            foreach ($param as $k => $v){

                $ret = Db::name('gift')->where('id',$k)->setField('code',$v);
            }
            if($ret !== false){
                win('科目代码设置成功',Url::build('index'));
            }
        }

    }


    /*
     * 排列顺序
     */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        if($id){
            foreach ($id as $key => $value) {
                Db::name('gift')->where('id', $value)->update(['sort' => $sort[$key]]);
            }
        }

        win('操作成功', Url::build('index', ['orderId' => 'sort']));
    }


    /**
     * 广告位编辑
     */
    public function update($id, Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();

            if (!empty($data['single_content']) && count($data['single_content']) != count(array_unique($data['single_content']))) {
                fail('不能添加重复分类');
            }
            // 验证
           // $validate = Loader::validate('AdType');
           // if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);


            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }
        $single_list = \app\console\model\Single::order(['sort' => 'asc','id' => 'asc'])->where(['auding_status' =>2,'is_delete'=>1])->where('parent_id',0)->select();
        $single_list2 = \app\console\model\Single::order(['sort' => 'asc','id' => 'asc'])->where(['auding_status' =>2,'is_delete'=>1])->where('parent_id','neq',0)->select();
        $single_list = getMenuTree($single_list);
        $item = Model::get($id);
        return $this->fetch('create', [
            'gift_count' => Db::name('gift_count')->where('gift_id',$id)->select(),
            'single_list' => json_encode($single_list),
            'single_list2' => json_encode($single_list2),
            'item' => $item
        ]);
    }

    /**
     * @param $id
     * @return bool
     * 礼包数量删除
     */
    public function gift_count($id)
    {
        $ret = Db::name('gift_count')->where('id',$id)->delete();
        if($ret){
            return true;
        }
        return false;
    }



    /**
     * 广告位删除
     */
    public function destroy($id, Model $model)
    {

        if (Request::instance()->isGet()) {
            auding_status($id,'title');
            win('操作成功', Url::build('index'));
        }
        fail('操作失败');

    }
    /**
     * 栏目状态改变
     */
    public function status($id, Request $request, Model $model)
    {
        $id = $request->instance()->param('id');

        $status = $model->where('id', $id)->value('status') == '1' ? 2 : 1;

        if ($model->where('id', $id)->update(['status' => $status])) {
            return $status;
        }
        return false;
    }


    /**
     * 栏目全部删除
     */
    public function destroyAll($id, AdTypeModel $adType)
    {

        if ($adType->amputateAll($id)) {

            win('操作成功', Url::build('AdType/index'));
        }

        fail('操作失败');

    }







    /**
     * 清除缓存
     */
    protected function clearCache()
    {
        Cache::rm('AdType');
    }
}